from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info import db
from info.models import News, User, Comment, CommentLike
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import news_blue
from flask import render_template

# 功能分析：关注＆取消关注
# 访问路径：/news/followed_user
# 访问方式：POST
# 访问参数：user_id(作者id),action
# 返回值：errno,errmsg
@news_blue.route('/followed_user', methods=['POST'])
@user_login_data
def followed_user():

    # 判断客户是否登陆
    if not g.user:
        return jsonify(errno=RET.SESSIONERR,errmsg='客户未登录')

    # 获取参数
    author_id = request.json.get('user_id')
    action = request.json.get('action')

    if not all([author_id,action]):
        return jsonify(errno=RET.DATAERR,errmsg='参数不全')

    if not action in ['follow','unfollow']:
        return jsonify(errno=RET.DATAERR,errmsg='操作类型有误')

    try:
        author = User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='获取用户失败')

    if not author: return jsonify(errno=RET.NODATA,errmsg='该作者不存在')

    try:
        if action == 'follow':
            if not g.user in author.followers:
                author.followers.append(g.user)
        else:
            if g.user in author.followers:
                author.followers.remove(g.user)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='操作失败')

    return jsonify(errno=RET.OK,errmsg='操作成功')


# 功能分析：点赞＆取消点赞处理
# 请求路径：/news/comment_like
# 请求方式：post
# 请求参数：comment_id,action.g.user
# 返回值：errno,errmsg
@news_blue.route('/comment_like', methods=['POST'])
@user_login_data
def comment_like():
    # 判断客户是否登陆
    if not g.user:
        return jsonify(errno=RET.DATAERR,errmsg='客户未登录')

    # 获取参数
    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    # 判断是否为空
    if not all([comment_id,action]):
        return jsonify(errno=RET.DATAERR,errmsg='参数不全')

    # 获取评论对象
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取评论失败')

    if not comment:
        return jsonify(errno=RET.DATAERR,errmsg='评论不存在')

    try:
        if action == 'add':
            # 判断该用户是否对该评论点过赞
            comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id, CommentLike.comment_id == comment.id).first()
            if not comment_like:
                # 创建点赞对象：
                comment_like = CommentLike()
                comment_like.comment_id = comment.id
                comment_like.user_id = g.user.id

                # 添加到数据库
                db.session.add(comment_like)

                # 该评论点赞数量加１
                comment.like_count +=1
                db.session.commit()
        else:
            # 判断该用户是否对该评论点过赞
            comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,CommentLike.comment_id == comment.id).first()

            if comment_like:
                # 移除点赞对象
                db.session.delete(comment_like)
                db.session.delete(comment_like)

                if comment.like_count > 0:
                    comment.like_count -=1
                db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR,errmsg='操作失败')

    return jsonify(errno=RET.OK,errmsg='操作成功')


# 新闻评论
# 请求方式：post
# 请求路径：/news/news_comment
# 请求参数：news_id,comment,parent_id,g.user
# 返回值：errno,errmsg,评论字典
@news_blue.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    # 判断用户是否登陆
    if not g.user:
        return jsonify(errno=RET.DATAERR,errmsg='用户未登录')

    # 获取参数
    news_id = request.json.get('news_id')
    content = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    # 不为空判断
    if not all([news_id,content]):
        return jsonify(error=RET.DATAERR,errmsg='请求参数不全')

    # 创建评论对象：
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = content

    # 判断父评论编号
    if parent_id:
        comment.parent_id = parent_id

    # 将评论添加到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR,errmsg='评论失败')

    # 返回响应
    return jsonify(errno=RET.OK,errmsg='评论成功',data = comment.to_dict())





# 功能分析：新闻收藏&取消收藏
# 请求方式：post
# 请求路径：/news/news_collect
# 请求参数：user.id,news.id,action
# 返回数据：errno,errmsg
@news_blue.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    # 获取用户对象
    # user_id = session.get('user_id')
    # user = None
    # try:
    #     user = User.query.get(user_id)
    # except Exception as e:
    #     current_app.logger.error(e)

    # 判断客户是否存在
    if not g.user:
        return jsonify(errno=RET.DATAERR,errmsg='未登录，请先登录')

    # 获取参数
    new_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([new_id,action]):
        return jsonify(errno=RET.DATAERR,errmsg='请求参数不全')

    # 根据新闻id获取新闻对象
    try:
        news = News.query.get(new_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻失败')

    # 判断新闻是否存在
    if not g.user:
        return jsonify(errno=RET.DATAERR,errmsg='新闻不存在')

    # 根据action的值判断是收藏还是取消
    if action == 'collect':
        if news not in g.user.collection_news:
            g.user.collection_news.append(news)
    else:
        if news in g.user.collection_news:
            g.user.collection_news.remove(news)

    return jsonify(errno=RET.OK,errmsg='收藏成功')


# 功能分析：新闻详情
# 请求方式:get
# 请求路径：/news/news_id
# 请求参数：news.id
# 返回数据：news.detail页面，用户data数据

@news_blue.route('/<int:news_id>')
@user_login_data
def new_detail(news_id):

    # user_id = session.get("user_id")
    #
    # # 获取用户登陆数据
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)


    # 根据news_id获取新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取新闻数据失败')
    # 判断是否存在
    if not news:
        abort(404)

    # 查询热门新闻的前5条数据
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(5).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    # 新闻列表转成字典列表
    click_news_list = []
    for new in news_list:
        click_news_list.append(new.to_dict())

    # 判断客户是否收藏
    is_collect = False
    if g.user and news.id in g.user.collection_news:
        is_collect = True

    # 查询该新闻的所有评论
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='获取评论失败')

    like_comment_ids = []
    if g.user:
        # 获取客户点赞列表
        try:
            comment_likes = CommentLike.query.filter(CommentLike.user_id == g.user.id).all()
        except Exception as e:
            current_app.logger.error(e)

        # 获取点赞列表id集合
        for comment_like in comment_likes:
            like_comment_ids.append(comment_like.comment_id)


    # 将评论列表转化成字典
    comment_list = []
    for comment in comments:
        # 给每条评论添加点赞属性,默认False
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if g.user and comment.id in like_comment_ids:
            comment_dict['is_like'] =True

        comment_list.append(comment_dict)

    # 判断该用户是否关注过该新闻作者-该用户在新闻作者的粉丝里（followers反向属性followed该作者被那些人关注）或该用户在该作者被那些人关注里
    is_follow = False
    # 方式１，
    # if g.user and news.user:
    #     if g.user in news.user.followers:
    #         is_follow = True
    # 方式２
    if g.user and news.user:
        if news.user in g.user.followed:
            is_follow = True


    data = {
        'news_info':news.to_dict(),
        'user_info':g.user.to_dict() if g.user else '',
        'click_news_list':click_news_list,
        'is_collect':is_collect,
        'comments':comment_list,
        'is_follow':is_follow
    }

    return render_template('news/detail.html',data=data)

